package com.ecloud.common.exception;

import com.ecloud.common.JsonResult;
import com.ecloud.common.ResultEnum;
import org.springframework.validation.BindException;

import java.time.format.DateTimeParseException;

/**
 * 异常处理器
 *
 * @author Squbi
 * @date 2021/3/31 14:00
 */
public class ExceptionHandleCenter {

    private ExceptionHandleCenter() {
    }

    public static JsonResult handle(Exception e) {
        if (e instanceof JsonResultException) {
            JsonResultException jre = (JsonResultException) e;
            return jre.getJsonResult();
        } else if (e instanceof InnerException) {
            InnerException ie = (InnerException) e;
            return JsonResult.failed(ResultEnum.SYS_ERROR, ie.getMsg());
        } else if (e instanceof ServerException) {
            ServerException se = (ServerException) e;
            return se.getMsg() == null ?
                    JsonResult.failed(se.getResult()) :
                    JsonResult.failed(se.getResult(), se.getMsg());
        } else if (e instanceof BindException) {
            return JsonResult.failed(ResultEnum.ARGS_ERR, e.getMessage());
        } else if (e instanceof DateTimeParseException) {
            return JsonResult.failed(ResultEnum.TIME_PARSE_ERROR);
        } else {
            e.printStackTrace();
            return JsonResult.failed(ResultEnum.SYS_ERROR, e.getMessage());
        }
    }
}
